package com.size.mall.item.controller;

import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.size.mall.mallapi.entity.PmsProductSaleAttr;
import com.size.mall.mallapi.entity.PmsSkuImage;
import com.size.mall.mallapi.entity.PmsSkuInfo;
import com.size.mall.mallapi.entity.PmsSkuSaleAttrValue;
import com.size.mall.mallapi.service.PmsProductSaleAttrService;
import com.size.mall.mallapi.service.PmsSkuImageService;
import com.size.mall.mallapi.service.PmsSkuInfoService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;

import java.util.HashMap;
import java.util.List;

@Controller
public class ItemController {

    @Reference
    PmsSkuInfoService pmsSkuInfoService;

    @Reference
    PmsSkuImageService pmsSkuImageService;

    @Reference
    PmsProductSaleAttrService pmsProductSaleAttrService;


    /**
     * 改为 基于skuid 的搜索 先检索出 spuid
     *
     * @param spuId
     * @param model
     *
     * @return
     */

    @GetMapping("{skuId}.html")
    public String getItem(@PathVariable("skuId") String skuId, ModelMap model) {

        PmsSkuInfo sku = pmsSkuInfoService.getById(skuId);


        //查询 sku信息
        String spuId = sku.getProductId();

        PmsSkuInfo skuInfo = pmsSkuInfoService.getInfo(spuId);

        // String skuId = skuInfo.getId();
        // 查询图片
        List<PmsSkuImage> imags = pmsSkuImageService.getImags(skuId);


        skuInfo.setSkuImageList(imags);
        model.put("skuInfo", skuInfo);


        // 罗列sku
        List<PmsProductSaleAttr> spuSaleAttr = pmsProductSaleAttrService.getPmsProductSaleAttr(spuId, skuId);

        model.put("spuSaleAttrListCheckBySku", spuSaleAttr);

        // 查询当前sku的其他sku
        List<PmsSkuInfo> skus = pmsSkuInfoService.getAllSku(skuInfo.getProductId());
        HashMap<String, String> skuHash = MapUtil.newHashMap();
        for (PmsSkuInfo skuI : skus) {

            String k = "";
            String v = skuI.getId();
            List<PmsSkuSaleAttrValue> pmsSkuSaleAttrValueList = skuI.getPmsSkuSaleAttrValueList();
            for (PmsSkuSaleAttrValue pmsSkuSaleAttrValue : pmsSkuSaleAttrValueList) {
                k += pmsSkuSaleAttrValue.getSaleAttrValueId() + "|"; //239|245

            }
            skuHash.put(k, v);
        }

        String skuHashJson = JSONUtil.toJsonStr(skuHash);

        model.put("skuHashJson", skuHashJson);

        return "item";
    }

}
